# -*- coding: utf-8 -*-

import tw_paths

from urllib import urlencode, quote as urlquote

def encode(text):
	return urlquote(text, safe='~')

def create_timestamp():
	from time import time
	return str(int(time()))

def create_nonce():
	from random import getrandbits
	return str(getrandbits(64))

def create_signature(key, message):
	import hmac
	from hashlib import sha1
	return hmac.new(key, message, sha1).digest().encode('base64')[:-1]

def get_params(data_plain):
	data_dict = {}
	for param in data_plain.split("&"):
		aux = param.split("=")
		data_dict[aux[0]] = aux[1]
	return data_dict
	

class OAuthManager(object):

	CONSUMER = {"KEY": "YJ1mvNCkorSaxABDqZl8A", "SECRET": "kBawGC1U6rPSZSvgqJzpF7OKoyPW3Cufeu0Hlp1Y"}
	REQUEST_TOKEN_URL = "https://api.twitter.com/oauth/request_token"
	AUTHORIZE_URL = "https://api.twitter.com/oauth/authorize"
	ACCESS_TOKEN_URL = "https://api.twitter.com/oauth/access_token"

	def get_data_from_signed_url(self, url, meth='GET', extra_params={}):
		import urllib2
		try:
			if meth == 'GET':
				f = urllib2.urlopen(self.get_signed_url(url, meth, extra_params))
			else:
				f = urllib2.urlopen(self.get_signed_url(url, meth, extra_params), '')
			data=f.read()
			f.close()
			return 'ok', data
		except urllib2.HTTPError, e:
			return 'httpError', str(e.code)
		except urllib2.URLError, e:  
			return 'urlError', str(e.reason)

	def get_signed_url(self, url, meth='GET',extra_params={}):
		return "%s?%s" % (url, self.get_signed_body(url, meth,extra_params))

	def get_signed_body(self, url, meth='GET',extra_params={}):
		kwargs = {
			'oauth_consumer_key': self.CONSUMER['KEY'],
			'oauth_signature_method': 'HMAC-SHA1',
			'oauth_version': '1.0',
			'oauth_timestamp': create_timestamp(),
			'oauth_nonce': create_nonce(),
			}
		kwargs.update(extra_params)
		#print kwargs
		if self.token is not None:
			kwargs['oauth_token'] = self.token['oauth_token']
			key = "%s&" % encode(self.CONSUMER['SECRET']) + encode(self.token['oauth_token_secret'])
		else:
			key = "%s&" % encode(self.CONSUMER['SECRET'])

		message = '&'.join(map(encode, [
			meth.upper(), url, '&'.join(
				'%s=%s' % (encode(k), encode(kwargs[k])) for k in sorted(kwargs)
				)
			]))
		kwargs['oauth_signature'] = create_signature(key, message)
		return urlencode(kwargs)

	def __init__(self, user):
		self.user = user
		self.token = None
			
	def get_access_token(self,token_plain):
		self.token = get_params(token_plain)
		
	def create_request_token(self):
		code, data = self.get_data_from_signed_url(self.REQUEST_TOKEN_URL)
		br_url = self.AUTHORIZE_URL + "?" + data + "&oauth_callback=oob"
		print br_url
		import webbrowser
		webbrowser.open(br_url)
		return get_params(data)
		
	def authorize(self,key,request_token):
		code, data = self.get_data_from_signed_url(self.ACCESS_TOKEN_URL,'POST',{'oauth_verifier': key, 'oauth_token': request_token['oauth_token']})
		if code == 'ok':
			self.save_access_token(data)
		return code
		
	def save_access_token(self, token):
		rx=open(tw_paths.ACCSS_TKNS_DIR + self.user,"w")
		rx.write(token)
		rx.close()
